/**
 * 
 */
package soa.security.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.ldap.query.ContainerCriteria;
import org.springframework.ldap.query.SearchScope;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Repository;

import soa.security.dao.RoleDao;
import soa.security.domain.Person;
import soa.security.domain.Role;

/**
 * @author Cre.Gu
 *
 */
@Repository
public class RoleDaoImpl extends SpringLdapDaoImpl<Role> implements RoleDao {

	@Override
	public void create(Role t) {
		t.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		ldapTemplate.create(t);
	}

	@Override
	public Role findByDn(String dn) {
		Role o = ldapTemplate.findByDn(LdapNameBuilder.newInstance(dn).build(),
				Role.class);
		o.setBid(LdapUtils.getStringValue(o.getDn(), o.getDn().size() - 1));
		return o;
	}

	@Override
	public List<Role> allRoles(String baseDn, SearchScope searchScope) {
		ContainerCriteria query = baseQuery(baseDn, searchScope);

		return ldapTemplate.search(query, new BaseContextMapper());
	}

	@Override
	public void addPersons(Role role, Person person) {
		addAttrName(role.getDn(), "persons", person.getDn().toString());
	}

	@Override
	public void removePersons(Role role, Person person) {
		removeAttrName(role.getDn(), "persons", person.getDn().toString());
	}

	@Override
	public List<String> allPersons(Role role) {
		return allAttrName(role.getDn(), "persons");
	}

	@Override
	public void addSubRoles(Role role, Role subRole) {
		addAttrName(role.getDn(), "children", subRole.getDn().toString());
	}

	@Override
	public void removeSubRoles(Role role, Role subRole) {
		removeAttrName(role.getDn(), "children", subRole.getDn().toString());
	}

	@Override
	public List<String> allSubRoles(Role role) {
		return allAttrName(role.getDn(), "children");
	}

	@Override
	public String getObjectClass() {
		return "zjtzsw-role";
	}

}
